package com.naihe.anderson.sms.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.adapter.HorizontalSmsAdapter;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.NhsmsSession;
import com.naihe.anderson.sms.listener.OnMenuDialogClickListener;
import com.naihe.anderson.sms.listener.OnNotifyDataSessionListener;
import com.naihe.anderson.sms.manager.NhSmsMgr;
import com.naihe.anderson.sms.util.Configure;
import com.naihe.anderson.sms.util.PxDipChangeUtil;
import com.naihe.anderson.sms.widgets.DragGrid;
import com.naihe.anderson.sms.widgets.PathMenuView;
import com.naihe.anderson.sms.widgets.ScrollLayout;
import com.naihe.anderson.sms.widgets.SystemAlertDialog;

public class MainSmsActivity extends Activity implements OnMenuDialogClickListener, OnNotifyDataSessionListener, OnClickListener{
	
	private static final int CONFIRMPASSWORD = 2011111;
	
	public static final int MSG_WHAT_MENU_OPEN_SESSION = 0;
	public static final int MSG_WHAT_MENU_DEL_SESSION = 1;
	public static final int MSG_WHAT_MENU_DEL_SESSION_GO = 7;
	public static final int MSG_WHAT_MENU_OPEN_CONTACT = 2;
	public static final int MSG_WHAT_MENU_MACK_CALL = 3;
	public static final int MSG_WHAT_MENU_COLLECTION_SESSION = 4;
	public static final int MSG_WHAT_GET_DATA_CHANGE = 5;
	public final static int MSG_WHAT_SHOW_PROGRESS_WHAT = 6;
	public final static int MSG_WHAT_HIDE_PATH_WHAT = 8;
	public final static int MSG_WHAT_SHOW_PASSWORD_DIALOG = 9;
	public final static int MSG_WHAT_HIDE_PATH_WHAT_NURMAL = 10;
	
	private NhSmsApp nhSmsApp;
	private NhSmsMgr nhSmsMgr;
	/** GridView. */
	private DragGrid gridView;
	private TextView tv_page;
	private ScrollLayout lstGroupViews;
	private PathMenuView pathMenuView;
	LinearLayout.LayoutParams param;

	TranslateAnimation left, right;
	Animation up, down;

	public static final int PAGE_SIZE = 8;
	ArrayList<DragGrid> gridviews = new ArrayList<DragGrid>();
	
	ArrayList<ArrayList<NhsmsSession>> pageSmsSessionlists = new ArrayList<ArrayList<NhsmsSession>>();//每一页的数据
	ArrayList<NhsmsSession> smsSessionlists = new ArrayList<NhsmsSession>();//全部数据的集合集
	
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_MENU_OPEN_SESSION://打开会话
				Intent intent = new Intent(MainSmsActivity.this, TalkMessageActivity.class);
				intent.putExtra("NhsmsSession", (NhsmsSession)msg.obj);
				startActivity(intent);
				break;
			case MSG_WHAT_MENU_DEL_SESSION_GO:
				nhSmsMgr.deleteNhSession((NhsmsSession)msg.obj);
				break;
			case MSG_WHAT_MENU_DEL_SESSION://删除会话
				NhsmsSession delSeesion = (NhsmsSession)msg.obj;
				if(!TextUtils.isEmpty(delSeesion.getCipher())){
					Toast.makeText(MainSmsActivity.this, getResources().getString(R.string.menu_popup_has_password), Toast.LENGTH_SHORT).show();
					return;
				}
				
				Message message = mHandler.obtainMessage();
				message.what = MSG_WHAT_MENU_DEL_SESSION_GO;
				message.obj = delSeesion;
				new SystemAlertDialog(MainSmsActivity.this, mHandler, 
						getResources().getString(R.string.menu_btn_text_menu_bottom), 
						getResources().getString(R.string.alert_del_content), 
						getResources().getString(R.string.cancel), 
						getResources().getString(R.string.ok), message).show();
				break;
			case MSG_WHAT_MENU_OPEN_CONTACT://打开对应联系人
				NhsmsSession nhsmsSession =  (NhsmsSession)msg.obj;
				if(nhSmsApp.getContactMgr().getContactUserById(nhsmsSession.getPerson()) != null){
					Intent intent2 = new Intent(Intent.ACTION_VIEW,Uri.parse("content://com.android.contacts/contacts/" + nhsmsSession.getPerson()));
					startActivity(intent2);
				} else {
//					Intent intent2 = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
//					intent2.putExtra("phone", nhsmsSession.getAddress());
//					startActivity(intent2);
					Intent intent2 = new Intent(Intent.ACTION_INSERT_OR_EDIT);
					intent2.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
					intent2.putExtra(ContactsContract.Intents.Insert.PHONE, nhsmsSession.getAddress());
					startActivity(intent2);
				}
				break;
			case MSG_WHAT_MENU_MACK_CALL://呼叫
				Intent intent3 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel://" + ((String)msg.obj) ));
				intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent3);
				break;
			case MSG_WHAT_MENU_COLLECTION_SESSION://加密
				NhsmsSession saveSession =  (NhsmsSession)msg.obj;
				initPopupWindows(saveSession);
				
				mPopupWindow.update();
				mPopupWindow.showAtLocation(findViewById(R.id.reloading_progress), Gravity.CENTER, 0, 0);
				break;
			case MSG_WHAT_GET_DATA_CHANGE://数据变化刷新
				initData();
//				if(dialog != null && dialog.isShowing())
//				{
//					dialog.cancel();
//					dialog.dismiss();
//				}
				if(!tv_page.isShown()){
					tv_page.setText("1/" + Configure.countPages);
					tv_page.setVisibility(View.VISIBLE);
				}
				pathMenuView.hideProgress();
				break;
			case MSG_WHAT_HIDE_PATH_WHAT_NURMAL:
				pathMenuView.hideProgress();
				break;
			case MSG_WHAT_SHOW_PROGRESS_WHAT:
//				dialog.show();
				pathMenuView.showProgress();
				break;
			case MSG_WHAT_HIDE_PATH_WHAT:
				if(pathMenuView.isAreButtonsShowing()){
					pathMenuView.pathMenuDoing();
				}
				break;
			case MSG_WHAT_SHOW_PASSWORD_DIALOG:
				Intent intent4 = new Intent(MainSmsActivity.this, ConfirmPasswordActivity.class);
				intent4.putExtra("inentAction", "MainSmsActivity");
				MainSmsActivity.this.startActivityForResult(intent4, CONFIRMPASSWORD);
				break;
			default:
				break;
			}
		}
	};
	
	PopupWindow mPopupWindow = null;
	EditText editText;
	private void initPopupWindows(NhsmsSession nhsmsSession){
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popunwindwow = mLayoutInflater.inflate( R.layout.popup_edit_layout, null);
        editText = (EditText) popunwindwow.findViewById(R.id.baseSignature_edit);
        Button checkbtn_cancel =(Button) popunwindwow.findViewById(R.id.checkbtn_cancel);
        Button checkbtn_ok =(Button) popunwindwow.findViewById(R.id.checkbtn_ok);
        TextView title_text = (TextView) popunwindwow.findViewById(R.id.title_text);
       
        editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editText.setHint(getResources().getString(R.string.save_key_word));
        if(!TextUtils.isEmpty(nhsmsSession.getCipher())){
        	title_text.setText(getResources().getString(R.string.menu_btn_text_menu_top_2));
        	checkbtn_ok.setText(getResources().getString(R.string.mima_btn_jiechu));
        } else {
        	title_text.setText(getResources().getString(R.string.menu_btn_text_menu_top_1));
        }
        checkbtn_cancel.setOnClickListener(MainSmsActivity.this);
        checkbtn_ok.setOnClickListener(MainSmsActivity.this);
        checkbtn_ok.setTag(nhsmsSession);
        
        mPopupWindow = new PopupWindow(popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());//点击窗口外消失  
        mPopupWindow.setOutsideTouchable(true);  
        mPopupWindow.setFocusable(true);
	}
	
	public void setCurPage(final int page) {
		Animation a = AnimationUtils.loadAnimation(MainSmsActivity.this, R.anim.scale_in);
		a.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				tv_page.setText((page + 1) + "/" + Configure.countPages);
				tv_page.startAnimation(AnimationUtils.loadAnimation(MainSmsActivity.this, R.anim.scale_out));
			}
		});
		tv_page.startAnimation(a);

	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		nhSmsApp = (NhSmsApp) getApplication();
		nhSmsMgr = nhSmsApp.getNhSmsMgr();
		
		nhSmsMgr.setDataSetChangForSessionListener(MainSmsActivity.this);
		
		if(!TextUtils.isEmpty(nhSmsMgr.getBaseSafetyCipher())){
			mHandler.sendEmptyMessage(MSG_WHAT_SHOW_PASSWORD_DIALOG);
		}
		init();
		initData();
		
		if(nhSmsMgr.isIfFinishToGetData()) {
			tv_page.setText("1/" + Configure.countPages);
			tv_page.setVisibility(View.VISIBLE);
		}

		lstGroupViews.setPageListener(new ScrollLayout.PageListener() {
			@Override
			public void page(int page) {
				setCurPage(page);
			}
		});
		
		lstGroupViews.setOnTopListener(new ScrollLayout.PageOnTopListener() {
			
			@Override
			public void onTopEvent() {
				mHandler.sendEmptyMessage(MSG_WHAT_HIDE_PATH_WHAT);
			}
		});
		
	}

	private void init() {
		Configure.init(MainSmsActivity.this);
		tv_page = (TextView) findViewById(R.id.tv_page);
		
		if(!nhSmsMgr.isIfFinishToGetData())
			mHandler.sendEmptyMessage(MSG_WHAT_SHOW_PROGRESS_WHAT);
			
		lstGroupViews = (ScrollLayout) findViewById(R.id.scrollLayout_views);
		pathMenuView = (PathMenuView) findViewById(R.id.path_menu_view);
		
		param = new LinearLayout.LayoutParams(
				android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.FILL_PARENT);
		param.rightMargin = (int)PxDipChangeUtil.dipToPx(50, MainSmsActivity.this);
		param.leftMargin = (int)PxDipChangeUtil.dipToPx(15, MainSmsActivity.this);
		param.topMargin = (int)PxDipChangeUtil.dipToPx(15, MainSmsActivity.this);
		if (gridView != null) {
			lstGroupViews.removeAllViews();
		}
	}
	
	private void initData(){
		smsSessionlists.clear();
		smsSessionlists.add(null);
		smsSessionlists.addAll(nhSmsMgr.getNsSmsSessionList());
		
		int tempCountPages = Configure.countPages;
		Configure.countPages = (int) Math.ceil(smsSessionlists.size() / (float) PAGE_SIZE);

		if(pageSmsSessionlists == null){
			pageSmsSessionlists = new ArrayList<ArrayList<NhsmsSession>>();
		}
		
		for(int i = 0 ; i < Configure.countPages ; i++){
			if(i >= pageSmsSessionlists.size())
				pageSmsSessionlists.add(new ArrayList<NhsmsSession>());
			else
				pageSmsSessionlists.get(i).clear();
			
			for (int j = PAGE_SIZE * i; j < (PAGE_SIZE * (i + 1) > smsSessionlists.size() ? smsSessionlists.size() : PAGE_SIZE * (i + 1)); j++) 
				pageSmsSessionlists.get(i).add(smsSessionlists.get(j));
		}
		
		if(tempCountPages < Configure.countPages){
			for (int i = tempCountPages; i < Configure.countPages; i++) {
				lstGroupViews.addView(addGridView(i));
			}
		} else if (tempCountPages > Configure.countPages){
			//移除activitygroup中的view
			lstGroupViews.removeViewAt(tempCountPages - 1);
			
			gridviews.remove(tempCountPages - Configure.countPages - 1);
			//移除数据
			pageSmsSessionlists.remove(tempCountPages - Configure.countPages - 1);
		}

		for(DragGrid dragGrid : gridviews){
			((HorizontalSmsAdapter)dragGrid.getAdapter()).notifyDataSetChanged();
		}
	}
	
	private LinearLayout addGridView(int i) {
		LinearLayout linear = new LinearLayout(MainSmsActivity.this);
		gridView = new DragGrid(MainSmsActivity.this, MainSmsActivity.this);
		gridView.setAdapter(new HorizontalSmsAdapter(MainSmsActivity.this, pageSmsSessionlists.get(i)));
		gridView.setNumColumns(2);
		gridView.setHorizontalSpacing(5);
		gridView.setVerticalSpacing(5);
		gridView.setCacheColorHint(Color.TRANSPARENT);
		gridView.setSelector(R.anim.grid_light);
		gridviews.add(gridView);
		linear.addView(gridviews.get(i), param);
		return linear;
	}

	@Override
	protected void onDestroy() {
		
		super.onDestroy();
	}
	
	@Override
	protected void onStop() {
		nhSmsApp.getNotificationMgr().cancelNotif();
		super.onStop();
	}

	@Override
	public void onOpenItemToCantact(NhsmsSession nhsmsSession) {
		Message message = mHandler.obtainMessage();
		message.what = MSG_WHAT_MENU_OPEN_CONTACT;
		message.obj = nhsmsSession;
		mHandler.sendMessage(message);
	}

	@Override
	public void onMakeCall(NhsmsSession nhsmsSession) {
		Message message = mHandler.obtainMessage();
		message.what = MSG_WHAT_MENU_MACK_CALL;
		message.obj = nhsmsSession.getAddress();
		mHandler.sendMessage(message);
		
	}

	@Override
	public void onDelNhSmsSession(NhsmsSession nhsmsSession) {
		Message message = mHandler.obtainMessage();
		message.what = MSG_WHAT_MENU_DEL_SESSION;
		message.obj = nhsmsSession;
		mHandler.sendMessage(message);
	}

	@Override
	public void onOpenSessionItem(NhsmsSession nhsmsSession) {
		Message message = mHandler.obtainMessage();
		message.what = MSG_WHAT_MENU_OPEN_SESSION;
		message.obj = nhsmsSession;
		mHandler.sendMessage(message);
	}

	@Override
	public void onCollectionSession(NhsmsSession nhsmsSession) {
		Message message = mHandler.obtainMessage();
		message.what = MSG_WHAT_MENU_COLLECTION_SESSION;
		message.obj = nhsmsSession;
		mHandler.sendMessage(message);
	}

	@Override
	public void onDataChanged() {
		mHandler.sendEmptyMessage(MSG_WHAT_GET_DATA_CHANGE);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK ){
			if(pathMenuView.isAreButtonsShowing()){
				pathMenuView.pathMenuDoing();
				return true;
			} else {
//				Intent homeItent= new Intent(Intent.ACTION_MAIN);
//				homeItent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用，必须加入new task标识
//				homeItent.addCategory(Intent.CATEGORY_HOME);
//				startActivity(homeItent);
				
				System.gc();
				return super.onKeyDown(keyCode, event);
			}
		} else if(keyCode == KeyEvent.KEYCODE_MENU){
			pathMenuView.pathMenuDoing();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void finalize() throws Throwable {
		
		super.finalize();
	}

	@Override
	protected void onResume() {
		nhSmsApp.getNotificationMgr().cancelNotif();
		super.onResume();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(CONFIRMPASSWORD == requestCode && resultCode != RESULT_OK){
			MainSmsActivity.this.finish();
		} else {
			if(nhSmsMgr.isIfFinishToGetData())
				mHandler.sendEmptyMessage(MSG_WHAT_HIDE_PATH_WHAT_NURMAL);
		}
		
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.checkbtn_cancel){
			mPopupWindow.dismiss();
		} else if(v.getId() == R.id.checkbtn_ok){
			NhsmsSession session = (NhsmsSession) v.getTag();
			String signature = editText.getText().toString().trim();
			if(!TextUtils.isEmpty(session.getCipher())){//解除
				if(session.getCipher().equals(signature)){
					//success
					nhSmsMgr.setNhSessionPassword(session.getTid(), "");
					mPopupWindow.dismiss();
					Toast.makeText(MainSmsActivity.this, getResources().getString(R.string.mima_jiechu_success), Toast.LENGTH_SHORT).show();
				} else {
					editText.setText("");
					Toast.makeText(MainSmsActivity.this, getResources().getString(R.string.mima_error), Toast.LENGTH_SHORT).show();
				}
	        } else {
	        	nhSmsMgr.setNhSessionPassword(session.getTid(), signature);
	        	mPopupWindow.dismiss();
	        	Toast.makeText(MainSmsActivity.this, getResources().getString(R.string.mima_set_success), Toast.LENGTH_SHORT).show();
	        }
		}
	}
}
		